<?php

//require_once('../models/authorization.php');
require_once('../models/post.php');

class PostController{
		
	function PostController(){
		
	}
	
	/**
	 * adds a new post
	 * 
	 * @param $title
	 * @param $post
	 * @param $category
	 */
	public static function addPost($title, $post, $cat, $comments){
		
		if(Post::addPost($title, $post, $cat, $comments))
			header("Location: index.php");
	}
	
	/**
	 * edit a current post
	 * 
	 * @param $title
	 * @param $post
	 * @param $cat
	 * @param $id
	 */
	function editPost($title, $post, $cat, $id){
		Post::editPost($title, $post, $cat, $id);
		header("Location: index.php");
	}
			
	/**
	 * returns an array of all the posts and all of their
	 * information in the database
	 * 
	 * @return array
	 */
	function getAllPosts(){
		
		$posts = array();
		foreach (Post::findAllPosts() as $p){
			array_push($posts, array("title" => $p->getTitle(),
									 "author" => $p->getAuthor(),
									 "date" => $p->getPostDate(),
									 "message" => $p->getEntry(),
									 "id" => $p->getId(),
									 "category" => $p->getCategoryName()));
		}
		return $posts;
	}
	
	/**
	 * returns the post with tha associated id
	 * 
	 * @param int post id
	 * @return Post post
	 */
	function getPostById($id){
	
		$posts = array();
		foreach(Post::findAllPosts() as $p){
			if($p->getId() == $id){
				return $p;
			}
		}	
		header("Location: error.php?error=postdoesnotexist");
		return null;
	}
	
	/**
	 * returns the posts that are within a specified category
	 * 
	 * @param int category id
	 * @return array of Post objects
	 */
	function getPostsByCategory($cat_id){
		
		$posts = array();
		foreach(Post::findAllPosts() as $p){
			if($p->getCategoryId() == $cat_id){
				array_push($posts, array("title" => $p->getTitle(),
									 	 "author" => $p->getAuthor(),
									     "date" => $p->getPostDate(),
									     "message" => $p->getEntry(),
									     "id" => $p->getId(),
									     "category" => $p->getCategoryName()));
			}
		}
		return $posts;
	}
	
	// TODO: should this method really be here, why not just call the
	// method in the model?
	function getNumberOfPosts(){
		return Post::getNumberOfPosts();
	}
}
?>
